package io.renren.common.key;

import com.google.gson.Gson;
import io.renren.common.exception.RRException;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.core.ApplicationContext;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import io.renren.common.utils.AESUtil;
import io.renren.common.utils.SpringContextUtils;
import io.renren.config.ConfigBeanValue;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

@Slf4j
public class keyConfig {

    private static keyConfig instance = new keyConfig();

    private ConfigBeanValue configBeanValue;

    //根密钥
    private String rootKey;

    //交易密钥
    private String transactionKey;

    private String transactionKeyDate;

    //MAC密钥
    private String MACkey;

    private String MACkeyDate;

    private keyConfig() {
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            configBeanValue = (ConfigBeanValue) SpringContextUtils.getBean("configBeanValue");
            String tmpRootKey = configBeanValue.rootKey;
            //这里要用base64解密
            rootKey = new String(decoder.decodeBuffer(tmpRootKey), "UTF-8");
        } catch (IOException e) {
            log.error("keyConfig异常", e);
        }
    }

    public static keyConfig getInstance() {
        return instance;
    }


    /**
     * 返回交易密钥
     *
     * @return
     */
    public String getTransactionKey() throws RRException {
        if (Strings.isEmpty(transactionKey)) {
            initTransKey();
        }
        if (!DateUtils.format(new Date()).equals(transactionKeyDate)) {
            initTransKey();
        }
        return transactionKey;
    }

    /**
     * 返回MAC密钥
     *
     * @return
     * @throws RRException
     */
    public String getMacKey() throws RRException {
        if (Strings.isEmpty(MACkey)) {
            initMacKey();
        }
        if (!DateUtils.format(new Date()).equals(MACkeyDate)) {
            initMacKey();
        }
        return MACkey;
    }


    /**
     * 初始化交易密钥
     *
     * @return
     */
    public String initTransKey() throws RRException {
        String url = configBeanValue.outConnClientGetTransforKey;//"http://localhost:8200/immovablespay/ivpay/getTransforKey";
        String Busi_code = "BDCZF";
        String City_code = "420113";
        String Unit_code = "000001";
        //返回交易密钥密文
        String tmpTranKey = "";
        String transKey = null;
        try {
            //访问签到接口
            String value = "&Busi_code=" + Busi_code;
            value = value + "&City_code=" + City_code;
            value = value + "&Unit_code=" + Unit_code;
            log.debug("查询参数：" + value);
            log.debug("查询路径：" + url);
            String retStr = HttpClientUtils.sendPost(url, value);
//            String retStr1 = URLDecoder.decode(retStr, "UTF-8");
//            log.debug("查询返回结果集(编码)：" + retStr1);
//            String retStr2 = AESUtil.Decrypt(retStr1, rootKey);
//            log.debug("查询返回结果集(解密)：" + retStr2);
            Map retMap = new Gson().fromJson(retStr, Map.class);
            if (retMap != null && "200".equals(retMap.get("rspcode"))) {
                tmpTranKey = retMap.get("transkey") + "";
                transKey = AESUtil.Decrypt(URLDecoder.decode(tmpTranKey, "UTF-8"), rootKey);
            } else {
                throw new RRException(retMap.get("rspmsg") + "", new Integer(retMap.get("rspcode") + ""));
            }

        } catch (Exception e) {
            log.error("initTransKey异常", e);
            throw new RRException(e.getMessage());
        }
        transactionKey = transKey;
        transactionKeyDate = DateUtils.format(new Date());
        return transKey;
    }


    /**
     * 初始化MAC密钥
     *
     * @return
     */
    public String initMacKey() throws RRException {
        String url = configBeanValue.outConnClientGetMacKey; //"http://localhost:8200/immovablespay/ivpay/getMacKey";
        String Busi_code = "BDCZF";
        String City_code = "420113";
        String Unit_code = "000001";
        //返回交易密钥密文
        String mackey = "";
        try {
            //访问签到接口
            String value = "&Busi_code=" + Busi_code;
            value = value + "&City_code=" + City_code;
            value = value + "&Unit_code=" + Unit_code;
            log.debug("查询参数：" + value);
            log.debug("查询路径：" + url);
            String retStr = HttpClientUtils.sendPost(url, value);
//            String retStr1 = URLDecoder.decode(retStr, "UTF-8");
//            log.debug("查询返回结果集(编码)：" + retStr1);
//            String retStr2 = AESUtil.Decrypt(retStr1, transactionKey);
//            log.debug("查询返回结果集(解密)：" + retStr2);
            Map retMap = new Gson().fromJson(retStr, Map.class);
            if (retMap != null && "200".equals(retMap.get("rspcode"))) {
                mackey = retMap.get("mackey") + "";
                mackey = AESUtil.Decrypt(URLDecoder.decode(mackey, "UTF-8"), transactionKey);
            } else {
                throw new RRException(retMap.get("rspmsg") + "", new Integer(retMap.get("rspcode") + ""));
            }

        } catch (Exception e) {
            log.error("initMacKey异常", e);
            throw new RRException(e.getMessage());
        }
        MACkey = mackey;
        MACkeyDate = DateUtils.format(new Date());
        return mackey;
    }
}
